// Relative time formatting
function getRelativeTime(isoString) {
    const serverNow = new Date(document.getElementById("server_now_utc").value);
    const dt = new Date(isoString);
    const diff = (serverNow - dt) / 1000; // seconds
    const absDiff = Math.abs(diff);
    const inStr = diff < 0 ? "in " : "";
    if (absDiff < 60) return "now";
    if (absDiff < 3_600) return inStr + " " + Math.floor(absDiff / 60) + " min";
    const hrs = Math.floor(absDiff / 3_600)
    if (hrs < 48) return inStr + " " + hrs + " hr" + (hrs == 1 ? '' : 's');
    const days = Math.floor(hrs / 24);
    if (days < 60) return inStr + " " + days + " day" + (days == 1 ? '' : 's');
    const mos = Math.floor(days / 30);
    if (mos < 24) return inStr + " " + mos + " mo" + (mos == 1 ? '' : 's');
    const yrs = Math.floor(mos / 12);
    return inStr + " " + yrs + " yr" + (yrs == 1 ? '' : 's');
}

function formatRelativeTime() {
    // Format all relative timestamps
    $(".relative-time").each(function() {
        const isoTime = $(this).attr("data-time");
        if (isoTime) {
            $(this).empty().append(getRelativeTime(isoTime));
            $(this).attr('title', (new Date(isoTime).toLocaleString()));
        }
    });
}